package com.zxl.designpattern.behavioral.state;

/**
 * 上下文类：自动贩卖机类
 * 维护当前状态并处理用户请求
 */
public class VendingMachine {
    private final State selectionState;      // 挑选状态
    private final State payingState;     // 支付状态
    private final State soldState;         // 已售出的状态
    private final State soldOutState;      // 售罄的状态
    
    private State currentState;      // 当前状态
    private int count;               // 商品数量
    private int price;               // 商品价格

    /**
     * 构造函数，初始化贩卖机
     * @param count 初始商品数量
     * @param price 商品价格
     */
    public VendingMachine(int count, int price) {
        selectionState = new SelectionProductState(this);
        payingState = new PayingState(this);
        soldState = new SoldState(this);
        soldOutState = new SoldOutState(this);
        
        this.count = count;
        this.price = price;

        // 根据初始库存设置状态
        if (count > 0) {
            currentState = selectionState;
        } else {
            currentState = soldOutState;
        }
    }
    
    // 处理用户支付
    public void pay(int amount) {
        currentState.pay(amount);
    }
    
    // 处理用户选择商品
    public void selectItem() {
        currentState.selectItem();
    }
    
    // 处理商品发放
    public void dispense() {
        currentState.dispense();
    }
    
    // 处理补货
    public void refill(int quantity) {
        currentState.refill(quantity);
    }
    
    // 释放商品
    public void releaseItem() {
        if (count > 0) {
            System.out.println("=== 发放商品 ===");
            count--;
        }
    }
    
    // 设置状态
    public void setState(State state) {
        this.currentState = state;
    }

    public void setCount(int newCount) {
        this.count = newCount;
    }

    // Getter方法
    public State getSelectionState() {
        return selectionState;
    }

    public State getPayState() {
        return payingState;
    }

    public State getSoldState() {
        return soldState;
    }

    public State getSoldOutState() {
        return soldOutState;
    }

    public int getCount() {
        return count;
    }

    public int getPrice() {
        return price;
    }
    
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("\n==== 自动贩卖机 ====\n");
        sb.append("商品价格: ").append(price).append("元\n");
        sb.append("当前库存: ").append(count).append("件\n");
        sb.append("当前状态: ").append(currentState.getClass().getSimpleName().replace("State", ""));
        return sb.toString();
    }

}